<?php

/**
 * 教学点经纬度获取工具类使用示例
 * 
 * 本文件展示了如何在不同场景中使用 OcationCoordinateHelper 类
 */

namespace app\common\library;

use app\common\library\OcationCoordinateHelper;

class OcationCoordinateUsageExample
{
    /**
     * 示例1：基本使用 - 获取单个教学点的经纬度
     */
    public function example1_basicUsage()
    {
        $ocationId = 1;
        
        // 获取完整的坐标信息（包含来源）
        $coordinates = OcationCoordinateHelper::getCoordinates($ocationId);
        
        echo "教学点ID: {$ocationId}\n";
        echo "经度: " . ($coordinates['longitude'] ?? '无') . "\n";
        echo "纬度: " . ($coordinates['latitude'] ?? '无') . "\n";
        echo "坐标来源: {$coordinates['source']}\n";
        
        /*
         * 可能的来源值：
         * - 'main': 来自主教学点
         * - 'child': 来自子教学点
         * - 'parent': 来自父教学点
         * - 'empty': 所有层级都没有坐标
         * - 'not_found': 教学点不存在
         * - 'none': 无效的教学点ID
         */
    }

    /**
     * 示例2：简化使用 - 只获取经纬度
     */
    public function example2_simpleUsage()
    {
        $ocationId = 1;
        
        // 只获取经纬度，不包含来源信息
        $coordinates = OcationCoordinateHelper::getSimpleCoordinates($ocationId);
        
        if ($coordinates['longitude'] && $coordinates['latitude']) {
            echo "教学点有坐标: {$coordinates['longitude']}, {$coordinates['latitude']}\n";
        } else {
            echo "教学点没有坐标\n";
        }
    }

    /**
     * 示例3：批量获取多个教学点的经纬度
     */
    public function example3_batchUsage()
    {
        $ocationIds = [1, 2, 3, 4, 5];
        
        // 批量获取坐标
        $batchCoordinates = OcationCoordinateHelper::getBatchCoordinates($ocationIds);
        
        foreach ($batchCoordinates as $ocationId => $coordinates) {
            echo "教学点{$ocationId}: ";
            if ($coordinates['longitude'] && $coordinates['latitude']) {
                echo "({$coordinates['longitude']}, {$coordinates['latitude']}) - 来源: {$coordinates['source']}\n";
            } else {
                echo "无坐标 - 原因: {$coordinates['source']}\n";
            }
        }
    }

    /**
     * 示例4：在控制器中使用 - 课程列表API
     */
    public function example4_inController()
    {
        // 模拟在控制器中的使用
        $courses = [
            ['id' => 1, 'name' => '数学课', 'ocation_id' => 1],
            ['id' => 2, 'name' => '语文课', 'ocation_id' => 2],
            ['id' => 3, 'name' => '英语课', 'ocation_id' => 3],
        ];

        // 为每个课程添加教学点坐标
        foreach ($courses as &$course) {
            $coordinates = OcationCoordinateHelper::getSimpleCoordinates($course['ocation_id']);
            $course['longitude'] = $coordinates['longitude'];
            $course['latitude'] = $coordinates['latitude'];
            $course['has_location'] = ($coordinates['longitude'] !== null && $coordinates['latitude'] !== null);
        }

        return $courses;
    }

    /**
     * 示例5：获取教学点层级结构信息
     */
    public function example5_hierarchyInfo()
    {
        $ocationId = 1;
        
        // 获取完整的坐标和层级信息
        $fullInfo = OcationCoordinateHelper::getFullCoordinateInfo($ocationId);
        
        echo "教学点ID: {$fullInfo['ocation_id']}\n";
        echo "是否有坐标: " . ($fullInfo['has_coordinates'] ? '是' : '否') . "\n";
        echo "坐标来源: {$fullInfo['coordinates']['source']}\n";
        
        if ($fullInfo['hierarchy']['main']) {
            echo "主教学点: {$fullInfo['hierarchy']['main']['name']}\n";
        }
        
        if ($fullInfo['hierarchy']['parent']) {
            echo "父教学点: {$fullInfo['hierarchy']['parent']['name']}\n";
        }
        
        if (!empty($fullInfo['hierarchy']['children'])) {
            echo "子教学点数量: " . count($fullInfo['hierarchy']['children']) . "\n";
        }
    }

    /**
     * 示例6：计算距离和获取最近的教学点
     */
    public function example6_distanceCalculation()
    {
        // 用户当前位置（例如：南宁市中心）
        $userLat = 22.8170;
        $userLng = 108.3669;
        
        // 要查询的教学点ID列表
        $ocationIds = [1, 2, 3, 4, 5];
        
        // 获取按距离排序的教学点
        $nearestOcations = OcationCoordinateHelper::getNearestOcations($ocationIds, $userLat, $userLng);
        
        echo "按距离排序的教学点：\n";
        foreach ($nearestOcations as $ocation) {
            echo "教学点{$ocation['ocation_id']}: {$ocation['distance']}公里 ";
            echo "({$ocation['coordinates']['longitude']}, {$ocation['coordinates']['latitude']}) ";
            echo "- 坐标来源: {$ocation['coordinates']['source']}\n";
        }
    }

    /**
     * 示例7：在地图显示中的应用
     */
    public function example7_mapDisplay()
    {
        $ocationIds = [1, 2, 3];
        
        // 获取用于地图显示的坐标数据
        $mapData = [];
        $batchCoordinates = OcationCoordinateHelper::getBatchCoordinates($ocationIds);
        
        foreach ($batchCoordinates as $ocationId => $coordinates) {
            if ($coordinates['longitude'] && $coordinates['latitude']) {
                $mapData[] = [
                    'id' => $ocationId,
                    'lng' => $coordinates['longitude'],
                    'lat' => $coordinates['latitude'],
                    'source' => $coordinates['source'],
                    'title' => "教学点{$ocationId}",
                    'icon' => $this->getIconBySource($coordinates['source'])
                ];
            }
        }
        
        return $mapData;
    }

    /**
     * 根据坐标来源获取不同的图标
     */
    private function getIconBySource($source)
    {
        $icons = [
            'main' => 'marker-blue.png',      // 主教学点用蓝色图标
            'child' => 'marker-green.png',    // 子教学点坐标用绿色图标
            'parent' => 'marker-orange.png'   // 父教学点坐标用橙色图标
        ];
        
        return $icons[$source] ?? 'marker-gray.png';
    }

    /**
     * 示例8：在课程搜索中的应用
     */
    public function example8_courseSearch($userLat = null, $userLng = null, $maxDistance = 10)
    {
        // 模拟课程数据
        $courses = [
            ['id' => 1, 'name' => '数学课', 'ocation_id' => 1],
            ['id' => 2, 'name' => '语文课', 'ocation_id' => 2],
            ['id' => 3, 'name' => '英语课', 'ocation_id' => 3],
        ];

        $result = [];
        
        foreach ($courses as $course) {
            $coordinates = OcationCoordinateHelper::getCoordinates($course['ocation_id']);
            
            // 如果教学点有坐标
            if ($coordinates['longitude'] && $coordinates['latitude']) {
                $courseData = $course;
                $courseData['longitude'] = $coordinates['longitude'];
                $courseData['latitude'] = $coordinates['latitude'];
                $courseData['coordinate_source'] = $coordinates['source'];
                
                // 如果提供了用户位置，计算距离
                if ($userLat && $userLng) {
                    $distance = OcationCoordinateHelper::calculateDistance(
                        $userLat, $userLng,
                        $coordinates['latitude'], $coordinates['longitude']
                    );
                    $courseData['distance'] = round($distance, 2);
                    
                    // 只返回指定距离内的课程
                    if ($distance <= $maxDistance) {
                        $result[] = $courseData;
                    }
                } else {
                    $result[] = $courseData;
                }
            }
        }
        
        // 如果有距离信息，按距离排序
        if ($userLat && $userLng) {
            usort($result, function($a, $b) {
                return $a['distance'] <=> $b['distance'];
            });
        }
        
        return $result;
    }

    /**
     * 示例9：数据验证和错误处理
     */
    public function example9_errorHandling()
    {
        $testCases = [
            0,      // 无效ID
            -1,     // 负数ID
            999999, // 不存在的ID
            1,      // 正常ID
            null,   // null值
            ''      // 空字符串
        ];

        foreach ($testCases as $ocationId) {
            echo "测试教学点ID: " . var_export($ocationId, true) . "\n";
            
            $coordinates = OcationCoordinateHelper::getCoordinates($ocationId);
            
            switch ($coordinates['source']) {
                case 'none':
                    echo "  结果: 无效的教学点ID\n";
                    break;
                case 'not_found':
                    echo "  结果: 教学点不存在\n";
                    break;
                case 'empty':
                    echo "  结果: 教学点存在但没有坐标\n";
                    break;
                default:
                    echo "  结果: 找到坐标 ({$coordinates['longitude']}, {$coordinates['latitude']}) - 来源: {$coordinates['source']}\n";
                    break;
            }
            echo "\n";
        }
    }

    /**
     * 示例10：性能优化 - 缓存坐标数据
     */
    public function example10_caching()
    {
        // 在实际应用中，可以结合缓存来提高性能
        $cacheKey = "ocation_coordinates_";
        $ocationId = 1;
        
        // 尝试从缓存获取
        $coordinates = cache($cacheKey . $ocationId);
        
        if (!$coordinates) {
            // 缓存中没有，从数据库获取
            $coordinates = OcationCoordinateHelper::getCoordinates($ocationId);
            
            // 存入缓存（缓存1小时）
            cache($cacheKey . $ocationId, $coordinates, 3600);
        }
        
        return $coordinates;
    }
}
